package com.zqs.compareface.server.camstream;

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: FaceCompare
 * @description:
 * @author: ZQS
 * @create: 2021-08-08 18:14
 */
public class CamStreamPull extends Thread {
    private String streamURL;// 流地址
    private String outputFile;// 文件路径

    public void setStreamURL(String streamURL) {
        this.streamURL = streamURL;
    }

    public void setOutputFile(String outputFile) {
        this.outputFile = outputFile;
    }
    public void pullStart(){
        start();
    }
    @Override
    public void run(){
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        //获取视频源
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(streamURL);
//        grabber.setFrameRate(30);
//        grabber.setImageWidth(640);
//        grabber.setImageHeight(480);

        // 流媒体输出地址，分辨率（长，高），是否录制音频（0:不录制/1:录制）
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile,640,480,1);
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_FLV1);
        recorder.setFormat("flv");
        recorder.setFrameRate(30);
        //一般考虑比推流器发送的视频比特流大，默认400000
        recorder.setVideoBitrate(800000);
        try {
            grabber.start();
            recorder.start();
            Frame frame = null;
            while ((frame = grabber.grabFrame()) != null) {
                recorder.record(frame);
                /**
                 * 我这里是做抽帧检测，可以休眠500毫秒
                 */
//                Thread.sleep(40);
                System.out.println(sdFormatter.format(System.currentTimeMillis()));
            }
            recorder.stop();
            grabber.stop();
        } catch (FFmpegFrameGrabber.Exception e) {
        e.printStackTrace();
        } catch (FFmpegFrameRecorder.Exception e) {
        e.printStackTrace();
        } catch (FrameGrabber.Exception e) {
        e.printStackTrace();
        } finally {
             if (grabber != null) {
                 try {
                     grabber.close();
                 } catch (FrameGrabber.Exception e) {
                     e.printStackTrace();
                 }
              }
        }
    }
}
